import 'dart:ui';

import 'package:flutter/material.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';

class Qinpaoinspect extends StatefulWidget {
  final Map param;
  Qinpaoinspect(this.param);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.param);
}

class _MyHomePageState extends State<Qinpaoinspect> {
  GlobalKey _globalKey;
  List formList;
  final Map param;
  bool select = false;
  String itemid;
  List<Offset> _points = <Offset>[];
  _MyHomePageState(this.param);
  initState() {
    super.initState();
    _globalKey = GlobalKey();
    formList = [
      {
        "title": '客户姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
  }

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        List tempimg1 =
            item.containsKey("urlArr1") ? item["urlArr1"] : new List();
        List tempimg = new List();
        tempimg.add(data["filename"]);
        tempimg.add(data["url"]);
        tempimg1.add(tempimg);
        setState(() {
          item["urlArr1"] = tempimg1;
        });
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    List postdata = param["post"];
    itemid = param["id"];
    // print(param);
    // print('传递数值');
    for (var item in postdata) {
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
            color: Colors.white,
            // height: height,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                    padding: new EdgeInsets.fromLTRB(10, 10, 0, 0),
                    child: new Row(
                      children: <Widget>[
                        new Text(item["name"]),
                        item["mustimg"] == "1"
                            ? Padding(
                                padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: new GestureDetector(
                                    onTap: () {
                                      photo(item);
                                    },
                                    child: new Image.asset(
                                      'resource/images/user/cremra.png',
                                      width: 20,
                                      height: 20,
                                      fit: BoxFit.contain,
                                    )))
                            : new Text('')
                      ],
                    )),
                item["item"] == ""
                    ? new TextField(

                        // controller: textEditingController,
                        onChanged: (value) {
                          print(value);
                          setState(() {
                            item['value'] = value;
                          });
                        },
                        decoration: InputDecoration(
                          hintText: item.containsKey("value")
                              ? item['value']
                              : '请填写相关信息',
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                        ))
                    : checkBox(item),
                item.containsKey("urlArr1") ? imgs(item) : new Text('')
              ],
            ),
            // child: new Row(
            //   children: <Widget>[
            //     Expanded(
            //       child: new Padding(
            //           padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
            //           child: new Text(
            //             item['name'],
            //             style: TextStyle(
            //                 fontSize: 15,
            //                 color: Color.fromRGBO(102, 102, 102, 1)),
            //           )),
            //       flex: 1,
            //     ),
            //     new Padding(
            //         padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
            //         child: new Text(
            //           item['id'],
            //           style:
            //               TextStyle(fontSize: 15, color: Color.fromRGBO(27, 182, 251, 1)),
            //         )),
            //   ],
          )));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget imgs(item) {
    List<Widget> tiles = [];
    Widget content;

    List items = item["urlArr1"];

    for (var i = 0; i < items.length; i++) {
      List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              Navigator.of(context).push(
                NinePicture(items, i),
              );
            },
            child: Image.network(temp1[1], width: 100, height: 100)),
      ));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    String defaultv = items[0];
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    } //设置选项默认值
    for (var i = 0; i < items.length; i++) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
          child: SizedBox(
              width: 22,
              child: Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: items[i],
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item['value'],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    setState(() {
                      select = true;
                      // defaultv = value;
                      item['value'] = value;
                    });
                  }))));

      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
          child: Text(items[i],
              style: new TextStyle(
                  fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

//   Widget build(BuildContext context) {
//     return WillPopScope(
//       child: new Scaffold(
//           appBar: new AppBar(
//             title: new Text(param["name"]),
//             backgroundColor: Colors.white,
//             iconTheme: new IconThemeData(color: Colors.black),
//             elevation: 0,
//             // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
//           ),
//           body: new Container(
//             margin: EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 0.0),
//             child: Column(children: <Widget>[
//               Container(
//                 height: 180.0,
//                 decoration: BoxDecoration(
//                   border: Border.all(color: Colors.grey, width: 0.5),
//                 ),
//                 child: RepaintBoundary(
//                   key: _globalKey,
//                   child: Stack(
//                     children: [
//                       GestureDetector(
//                         onPanUpdate: (DragUpdateDetails details) {
// //                                       //按下
//                           RenderBox referenceBox = context.findRenderObject();
//                           Offset localPosition = referenceBox
//                               .globalToLocal(details.globalPosition);
//                           setState(() {
//                             _points = new List.from(_points)
//                               ..add(localPosition);
// //              _points.add(localPosition);
//                           });
//                         },
//                         onPanEnd: (DragEndDetails details) =>
//                             _points.add(null), //抬起来
//                       ),
//                       CustomPaint(painter: new SignaturePainter(_points)),
//                     ],
//                   ),
//                 ),
//               )
//             ]),
//           )
// //           new Center(
// //               child: Container(
// //                   decoration: new BoxDecoration(
// //                     //color: Colors.white
// //                     color: Color.fromRGBO(238, 238, 238, 1),
// //                   ),
// //                   child: new ListView(
// //                     children: <Widget>[
// //                       // Align(
// //                       //     alignment: Alignment.topCenter,
// //                          // child:
// //                            Container(
// //                             color: Colors.white,
// //                             width: double.infinity,
// //                             height: 200,
// //                             padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
// //                             child: RepaintBoundary(
// //                               key: _globalKey,
// //                               child: Stack(
// //                                 children: [
// //                                   new Image.asset("resource/images/jiance/qinpao.png",fit: BoxFit.fitHeight,),
// //                                   GestureDetector(
// //                                     onPanUpdate: (DragUpdateDetails details) {
// //                                       //按下
// //                                       RenderBox referenceBox =
// //                                           context.findRenderObject();
// //                                       Offset localPosition =
// //                                           referenceBox.globalToLocal(
// //                                               details.globalPosition);
// //                                       setState(() {
// //                                         _points = new List.from(_points)
// //                                           ..add(localPosition);
// // //              _points.add(localPosition);
// //                                       });
// //                                     },
// //                                     onPanEnd: (DragEndDetails details) =>
// //                                         _points.add(null), //抬起来
// //                                   ),
// //                                   CustomPaint(
// //                                       painter: new SignaturePainter(_points)),
// //                                 ],
// //                               ),
// //                             ),

// //                           )]),
// //                       // Align(
// //                       //     alignment: Alignment.bottomCenter,
// //                       //     child: Padding(
// //                       //       padding: new EdgeInsets.fromLTRB(
// //                       //           0, param["mustmodel"] == "1" ? 300 : 0, 0, 10),
// //                       //       child: new ListView(
// //                       //           children: <Widget>[buildcontent()]),
// //                       //     )),

// //                   )
// //                   // Padding(
// //                   //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
// //                   //     child: new ListView(
// //                   //       children: <Widget>[buildcontent()],
// //                   //     )),
// //                   )
//           ),
//       onWillPop: () => willpop(),
//     );
//   }

  Widget build(BuildContext context) {
     AppBar appBar = AppBar(
            title: new Text(param["name"]),
            backgroundColor: Colors.white,
            iconTheme: new IconThemeData(color: Colors.black),
            elevation: 0,
            // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
          );
    return 
       new Scaffold(
          appBar: appBar,
          // new AppBar(
          //   title: new Text(param["name"]),
          //   backgroundColor: Colors.white,
          //   iconTheme: new IconThemeData(color: Colors.black),
          //   elevation: 0,
          //   // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
          // ),
          body: new Center(
              child: Container(
                  decoration: new BoxDecoration(
                    //color: Colors.white
                    color: Color.fromRGBO(238, 238, 238, 1),
                  ),
                  child: Stack(
                    children: <Widget>[
                      Align(
                          alignment: Alignment.topCenter,
                          child: Container(
                            color: Colors.white,
                            width: double.infinity,
                            height: param["mustmodel"] == "1" ? 200 : 0,
                            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
                            child: RepaintBoundary(
                              key: _globalKey,
                              child: Stack(
                                children: [
                                  new Image.asset("resource/images/jiance/qinpao.png",fit: BoxFit.fitHeight,),
                                  GestureDetector(
                                    onPanUpdate: (DragUpdateDetails details) {
                                      //按下
                                      RenderBox referenceBox =
                                          context.findRenderObject();
                                         // Offset localPosition =  referenceBox.localToGlobal(Offset.zero);
                                      var localPosition =
                                          referenceBox.globalToLocal(
                                              details.globalPosition);
                                              // Offset dys = [100.00,100.00];
                                              // localPosition.dy=100.00;
                                              
                                              //localPosition.y=localPosition.dy-64;
                                      setState(() {
                                        _points = new List.from(_points)
                                          ..add(Offset(localPosition.dx, localPosition.dy-appBar.preferredSize.height-20) );
                                        // _points = new List.from(_points)
                                        //   ..add(localPosition);
//              _points.add(localPosition);
                                      });
                                    },
                                    onPanEnd: (DragEndDetails details) =>
                                        _points.add(null), //抬起来
                                  ),
                                  CustomPaint(
                                      painter: new SignaturePainter(_points)),
                                ],
                              ),
                            ),
//                               child: new Stack(
//                                 children: [
//                                   new Image.asset("resource/images/jiance/qinpao.png"),
//                                   Positioned(
//                                     // top: 0.0,
//                                     // bottom: 0.0,
//                                     // left: 0.0,
//                                     // right: 0.0,
//                                     height: 300,
//                                     child:
//                                   GestureDetector(
//                                     //手势探测器，一个特殊的widget，想要给一个widge添加手势，直接用这货包裹起来
//                                     onPanUpdate: (DragUpdateDetails details) {
//                                       //按下
//                                       RenderBox referenceBox =
//                                           context.findRenderObject();
//                                       Offset localPosition =
//                                           referenceBox.globalToLocal(
//                                               details.globalPosition);
//                                       setState(() {
//                                         _points = new List.from(_points)
//                                           ..add(localPosition);
// //              _points.add(localPosition);
//                                       });
//                                     },
//                                     onPanEnd: (DragEndDetails details) =>
//                                         _points.add(null), //抬起来
//                                   )),
//                                   CustomPaint(
//                                       painter: new SignaturePainter(_points))
//                                 ],

//                                 //color: Colors.red,
//                                 //color: Colors.red,
//                                 // child: Align(
//                                 //     alignment: Alignment.topCenter,
//                                 //     child: param["mustmodel"] == "1"?showProblem():new Text(""),
//                                 //     )),
//                               )
                          )),
                      Align(
                          alignment: Alignment.bottomCenter,
                          child: Padding(
                            padding: new EdgeInsets.fromLTRB(
                                0, param["mustmodel"] == "1" ? 200 : 0, 0, 10),
                            child: new ListView(
                                children: <Widget>[buildcontent()]),
                          )),
                    ],
                  )
                  // Padding(
                  //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                  //     child: new ListView(
                  //       children: <Widget>[buildcontent()],
                  //     )),
                  )));
     
    
//     AppBar appBar = AppBar(
//             title: new Text(param["name"]),
//             backgroundColor: Colors.white,
//             iconTheme: new IconThemeData(color: Colors.black),
//             elevation: 0,
//             // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
//           );
//     return WillPopScope(
//       child: new Scaffold(
//           appBar: appBar,
//           // new AppBar(
//           //   title: new Text(param["name"]),
//           //   backgroundColor: Colors.white,
//           //   iconTheme: new IconThemeData(color: Colors.black),
//           //   elevation: 0,
//           //   // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
//           // ),
//           body: new Center(
//               child: Container(
//                   decoration: new BoxDecoration(
//                     //color: Colors.white
//                     color: Color.fromRGBO(238, 238, 238, 1),
//                   ),
//                   child: Stack(
//                     children: <Widget>[
//                       Align(
//                           alignment: Alignment.topCenter,
//                           child: Container(
//                             color: Colors.white,
//                             width: double.infinity,
//                             height: param["mustmodel"] == "1" ? 200 : 0,
//                             padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
//                             child: RepaintBoundary(
//                               key: _globalKey,
//                               child: Stack(
//                                 children: [
//                                   new Image.asset("resource/images/jiance/qinpao.png",fit: BoxFit.fitHeight,),
//                                   GestureDetector(
//                                     onPanUpdate: (DragUpdateDetails details) {
//                                       //按下
//                                       RenderBox referenceBox =
//                                           context.findRenderObject();
//                                          // Offset localPosition =  referenceBox.localToGlobal(Offset.zero);
//                                       var localPosition =
//                                           referenceBox.globalToLocal(
//                                               details.globalPosition);
//                                               // Offset dys = [100.00,100.00];
//                                               // localPosition.dy=100.00;
                                              
//                                               //localPosition.y=localPosition.dy-64;
//                                       setState(() {
//                                         _points = new List.from(_points)
//                                           ..add(Offset(localPosition.dx, localPosition.dy-appBar.preferredSize.height-20) );
//                                         // _points = new List.from(_points)
//                                         //   ..add(localPosition);
// //              _points.add(localPosition);
//                                       });
//                                     },
//                                     onPanEnd: (DragEndDetails details) =>
//                                         _points.add(null), //抬起来
//                                   ),
//                                   CustomPaint(
//                                       painter: new SignaturePainter(_points)),
//                                 ],
//                               ),
//                             ),
// //                               child: new Stack(
// //                                 children: [
// //                                   new Image.asset("resource/images/jiance/qinpao.png"),
// //                                   Positioned(
// //                                     // top: 0.0,
// //                                     // bottom: 0.0,
// //                                     // left: 0.0,
// //                                     // right: 0.0,
// //                                     height: 300,
// //                                     child:
// //                                   GestureDetector(
// //                                     //手势探测器，一个特殊的widget，想要给一个widge添加手势，直接用这货包裹起来
// //                                     onPanUpdate: (DragUpdateDetails details) {
// //                                       //按下
// //                                       RenderBox referenceBox =
// //                                           context.findRenderObject();
// //                                       Offset localPosition =
// //                                           referenceBox.globalToLocal(
// //                                               details.globalPosition);
// //                                       setState(() {
// //                                         _points = new List.from(_points)
// //                                           ..add(localPosition);
// // //              _points.add(localPosition);
// //                                       });
// //                                     },
// //                                     onPanEnd: (DragEndDetails details) =>
// //                                         _points.add(null), //抬起来
// //                                   )),
// //                                   CustomPaint(
// //                                       painter: new SignaturePainter(_points))
// //                                 ],

// //                                 //color: Colors.red,
// //                                 //color: Colors.red,
// //                                 // child: Align(
// //                                 //     alignment: Alignment.topCenter,
// //                                 //     child: param["mustmodel"] == "1"?showProblem():new Text(""),
// //                                 //     )),
// //                               )
//                           )),
//                       Align(
//                           alignment: Alignment.bottomCenter,
//                           child: Padding(
//                             padding: new EdgeInsets.fromLTRB(
//                                 0, param["mustmodel"] == "1" ? 200 : 0, 0, 10),
//                             child: new ListView(
//                                 children: <Widget>[buildcontent()]),
//                           )),
//                     ],
//                   )
//                   // Padding(
//                   //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
//                   //     child: new ListView(
//                   //       children: <Widget>[buildcontent()],
//                   //     )),
//                   ))),
//       onWillPop: () => willpop(),
//     );
  }

  //异常图片
  Widget showProblem() {
    List postData = param["post"];
    String modelUrl = "resource/images/jiance/carmodel2.png";
    if (postData[0]["post_id"] == "3043") {
      //结构件
      modelUrl = "resource/images/jiance/model/jiegou/jiegou.jpg";
    } else if (postData[0]["post_id"] == "3044") {
      //浸泡检测
      modelUrl = "resource/images/jiance/qinpao.png";
    }
    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );

    // List postData = param["post"];
    for (var i = 0; i < postData.length; i++) {
      var item = postData[i];
      List<String> items = item["item"].split(',');

      var id = item["id"];
      print(id);
      if (item.containsKey("value")) {
        if (items[0] != item["value"]) {
          //有异常情况
          String urls;
          if (item["post_id"] == "3043") {
            urls =
                'resource/images/jiance/model/jiegou/' + id.toString() + '.png';
          } else
            urls =
                'resource/images/jiance/model/qimian/' + id.toString() + '.png';

          File imgs = File(urls);
          var dir_bool = imgs.exists();
          print(dir_bool);
          print(urls);
          tiles.add(
            Positioned(
                //     child: new Image.asset(
                //   'resource/images/jiance/xlgx.png'
                //   //fit:BoxFit.none
                //   //fit: BoxFit.fi,
                // )
                child: new Image.asset(urls
                    //fit:BoxFit.none
                    //fit: BoxFit.fi,
                    )),
          );
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  Future<bool> willpop() {
    _showDialog();
    return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                   // sleep(Duration(seconds: 1));
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);

  final List<Offset> points; // Offset:一个不可变的2D浮点偏移。

  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint() //设置笔的属性
      ..color = Colors.red[800]
      ..strokeCap = StrokeCap.round
      ..isAntiAlias = true
      ..strokeWidth = 2.0
      ..strokeJoin = StrokeJoin.bevel;

    for (int i = 0; i < points.length - 1; i++) {
      //画线
      if (points[i] != null && points[i + 1] != null)
        canvas.drawLine(points[i], points[i + 1],
            paint); //drawLine(Offset p1, Offset p2, Paint paint) → void
//      canvas.drawOval(
//          new Rect.fromCircle(center: points[i], radius: 20.0), paint);
////      canvas.drawOval(rect, paint)
//    canvas.drawCircle(points[i], 20.0, paint);
    }
  }

  /**
   * 是否重绘
   */
  bool shouldRepaint(SignaturePainter other) => other.points != points;
//  bool shouldRepaint(SignaturePainter other) =>true;
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
